<?php

namespace App\Task;

use App\Model\Applet;
use App\Model\AppletPlayletRel;
use App\Model\DataPaymentRefund;
use App\Model\Payment;
use App\Model\Playlet;
use App\Model\PlayletEpisodes;
use App\Model\SystemOrderRefund;
use GuzzleHttp\Client;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\DbConnection\Db;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use Psr\Log\LoggerInterface;

class DyRefundOrderTask
{
    protected LoggerInterface $logger;

    public static $getTokenUrl = "https://open.douyin.com/oauth/client_token/";

    public static $getrefundOrderUrl = "https://open.douyin.com/api/trade_basic/v1/developer/refund_query/";
    public function __construct(protected LoggerFactory $loggerFactory)
    {
        $this->logger = $this->loggerFactory->get('log', 'dyRefundOrder');
    }
    public function execute()
    {
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------开始获取审核通过的短剧');
        //获取需要获取任务的视频

        try {
            $reFundsData = DataPaymentRefund::query()->select(['id','payment_id','payment_applet_id','payment_user_id','refund_dy_order_id'])->where(['status' => 2,'type' => 2])->get();
            if($reFundsData->isNotEmpty()){
                foreach ($reFundsData as $reFundsDatum){
                    //查询小程序的ID 获取appID 和密钥
                    $this->logger->info('查询小程序的ID 获取appID 和密钥');
                    $appletInfo = Applet::query()->where('id',$reFundsDatum->payment_applet_id)
                        ->where(['type' => 2])->select(['id','name','app_id','app_secret'])->first();

                    if(!empty($appletInfo)) {

                        $this->logger->info('获取此退款订单的的小程序token:'.$appletInfo->name);
                        $accessToken = $this->getDyAccessToken($appletInfo->id,$appletInfo->app_id,$appletInfo->app_secret);
//                            $accessToken = env('DY_TEST_TOKEN');
                        if(!empty($accessToken)){

                            $orderResult = $this->checkDyOrder($reFundsDatum->refund_dy_order_id,$accessToken);
//                            var_dump($orderResult);
//                            exit();
                            if(!empty($orderResult['refund_list'])){
                                $orderInfo = $orderResult['refund_list'][0];
                                $this->logger->info('订单状态为:'.$orderInfo['refund_status']);
                                //7订单退款失败
                                if($orderInfo['refund_status'] == 'FAIL'){
                                    $reFundsDatum->status = 4;
                                    $reFundsDatum->save();
                                    //8用户退款成功
                                }else if($orderInfo['refund_status'] == 'SUCCESS') {
                                    $reFundsDatum->status = 3;
                                    $reFundsDatum->refund_at = date('Y-m-d H:i:s', $orderInfo['refund_at']/1000);
                                    $this->updatePayment($reFundsDatum->payment_id);
                                    $reFundsDatum->save();
                                }
                            }else{
                                $this->logger->error('此退款单获取失败',[$reFundsDatum->id]);
                            }
                        }else{
                            $this->logger->error('小程序:'.$appletInfo->name.' 没有对应的token');
                        }
                    }else{
                        $this->logger->info('此退款订单没有对应的小程序',[$reFundsDatum->id]);
                    }
                }

            }else{
                $this->logger->info('没有需要查询的退款订单');
            }
        }catch (\Exception $e){
            $this->logger->error('请求退款订单|错误：' . $e->getLine() . '|' . $e->getMessage());
        }

        $this->logger->info(date('Y-m-d H:i:s') . '------------------------结束定时退款订单');
    }

    public function updatePayment($payment_id){


        $paymentInfo = Payment::query()->select(['id','pay_time'])->where(['id' => $payment_id,'status' => 2])->first();
        if(!empty($paymentInfo)){
            $paymentInfo->status = 4;
            $paymentInfo->save();
            //插入
            SystemOrderRefund::create([
                'payment_id' => $paymentInfo->id,
                'date' => date('Y-m-d',strtotime($paymentInfo->pay_time)),
                'status' => 1,
            ]);
        }
    }


    public function getDyAccessToken($applet_id,$app_id,$app_secret){

        $container = ApplicationContext::getContainer();

        $redis = $container->get(\Hyperf\Redis\RedisFactory::class)->get('dy');

        $key = 'dy_admin_access_token';
        $key .= $applet_id;
        $accessToken = $redis->get($key);
        if(empty($accessToken)){
            $params         = [
                'grant_type' => 'client_credential',
                'client_key'    => $app_id,
                'client_secret'   => $app_secret
            ];
            //获取token
            $accessTokenInfo     = $this->request($params, self::$getTokenUrl,'POST');
            if (!empty($accessTokenInfo['data']['access_token'])){
                $accessToken = $accessTokenInfo['data']['access_token'];
                $redis->setex($key,7100,$accessToken);
            }else{
                $accessToken = "";
            }
        }
        $this->logger->info('抖音token为：'.$accessToken);
        return $accessToken;
    }
    /**
     * 检查抖音订单
     */
    public function checkDyOrder($order_id,$accessToken){

        $params = [
            'refund_id'=>$order_id,
        ];
        $url = self::$getrefundOrderUrl;
        $orderResult  = $this->request($params,$url, 'POST',$accessToken);
        if($orderResult['err_no'] == 0){
            $this->logger->info('调用退款订单查询接口成功 返回数据：'.PHP_EOL.var_export(['result' => $orderResult], true));
            return $orderResult['data'];

        }else{
            $this->logger->error('调用媒资接口失败 返回数据：'.PHP_EOL.var_export(['result' => $orderResult], true));
        }
        return false;
    }
    /**
     * 传入数组进行HTTP POST请求
     */
    function request(array $params, string $url,string $method,string $access_token = null)
    {
        $client   = new Client([
            'timeout' => 3
        ]);
        $headers       = ['Content-Type' => 'application/json'];
        if(!empty($access_token)){
            $headers['access-token'] = $access_token;
        }

        $requestParams = [
            'headers' => $headers,
        ];
        if ($method == 'GET') {
            $requestParams['query'] = $params;
        } else {
            $requestParams['json'] = $params;//json_encode($params,JSON_UNESCAPED_UNICODE);
        }
        $response = $client->request($method,$url, $requestParams);
        if ($response->getStatusCode() !== 200) {
            return '';
        }
        $result   = $response->getBody()->getContents();
        $resultArr = json_decode($result,true);
        return $resultArr;

    }
}